package spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.executor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.TaskItemAllotTask;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.task.TaskItem;

import java.util.Iterator;
import java.util.List;

/**
 * executor下线，摘取该executor运行的所有非本地模式作业，移除该executor
 */
@Slf4j
@Setter
@Getter
public class ExecutorOfflineTaskItemAllotTask extends TaskItemAllotTask {
    private String executorId;

    public ExecutorOfflineTaskItemAllotTask(String executorId, AllotTaskItemService allotTaskItemService) {
        super(allotTaskItemService);
        this.executorId = executorId;
    }

    @Override
    protected void logStartInfo() {
        log.info("Execute the {} with {} offline", this.getClass().getSimpleName(), executorId);
    }

    /**
     * 失去流量同时下线
     *
     * @param taskIdList                   该域下所有作业
     * @param enableTaskIdList             该域下所有启用的作业
     * @param taskItemList                 默认为空集合
     * @param onlineExecutorList           默认为当前存储的数据，如果不想使用存储数据，请重写{@link #customLastOnlineExecutorList()}}方法
     * @param onlineOwnTrafficExecutorList lastOnlineExecutorList中所有noTraffic为false的Executor，注意Executor是同一个对象
     * @return
     * @throws Exception
     */
    @Override
    protected boolean pick(List<String> taskIdList,//
                           List<String> enableTaskIdList,//
                           List<TaskItem> taskItemList,//
                           List<Executor> onlineExecutorList,//
                           List<Executor> onlineOwnTrafficExecutorList) throws Exception {
        /**
         * 摘取下线的executor全部Shard
         */
        Executor targetExecutor = null;
        Iterator<Executor> iterator = onlineExecutorList.iterator();
        while (iterator.hasNext()) {
            Executor executor = iterator.next();
            if (executor.getExecutorId().equals(executorId)) {
                targetExecutor = executor;
                iterator.remove();
                taskItemList.addAll(executor.getTaskItemList());
                break;
            }
        }

        if (targetExecutor != null) {
            Iterator<Executor> $iterator = onlineOwnTrafficExecutorList.iterator();
            while ($iterator.hasNext()) {
                Executor executor = $iterator.next();
                if (targetExecutor.equals(executor)) {
                    $iterator.remove();
                    break;
                }
            }
        }

        // 如果该executor实际上已经在此之前下线，则摘取失败
        return targetExecutor != null;
    }

}
